package cd.safe.school.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import cd.safe.school.bean.FileItem;

public class NetTool {
	/**
	 * 从输入流中读取文本内容
	 * 
	 * @param in
	 * @param encoding
	 * @return
	 */
	public static String getContent(InputStream in, String encoding)
			throws Exception {
		// 创建内存字节数组输入流来存放读到字节码
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		// 从输入流中读取内容
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = in.read(buffer)) > 0) {
			// 边读就边往输出流中写内容
			out.write(buffer, 0, len);
		}
		out.close();
		in.close();
		String ret = out.toString(encoding == null ? "utf-8" : encoding);
		return ret;
	}

	/**
	 * 上传文件
	 * 
	 * @param url
	 * @param params
	 *            字段参数
	 * @param items
	 *            文件项集合
	 * @return
	 */
	public static String postFileFormParams(String url,
			Map<String, Object> params, List<FileItem> items) {
		String ret = null;
		try {
			URL u = new URL(url);

			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			String boundray = "---------------------------7dc2de3a31418";
			// /设置请求头
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + boundray);
			// 字段的确分隔符比头里面的分隔前面多“--”
			boundray = "--" + boundray;
			
			OutputStream out = conn.getOutputStream();
			
			// 上传普通的表单项
			for (Map.Entry<String, Object> en : params.entrySet()) {
				
				String filedName = en.getKey();
				String value = en.getValue().toString();
				// 写第一个字段
				out.write(boundray.getBytes());
				out.write("\r\n".getBytes());
				out.write(("Content-Disposition: form-data; name=\""
						+ filedName + "\"").getBytes());
				out.write("\r\n".getBytes());
				out.write("\r\n".getBytes());
				out.write(value.getBytes());
				out.write("\r\n".getBytes());
			}

			// 处理文件上传表单项
			for (FileItem fi : items) {
				out.write(boundray.getBytes());
				out.write("\r\n".getBytes());
				out.write(("Content-Disposition: form-data; name=\""
						+ fi.getFieldName() + "\"; filename=\"" + fi.getName() + "\"")
						.getBytes());
				out.write("\r\n".getBytes());
				out.write(("Content-Type: " + fi.getContentType()).getBytes());
				out.write("\r\n".getBytes());
				out.write("\r\n".getBytes());
				// 写附件中的内容,文件体
				InputStream in = fi.getStream();
				if (in == null) {
					in = new FileInputStream(fi.getPath());
				}
				// 把InputStream东西读出来，并往OutputStream写
				byte[] buffer = new byte[1024];
				int len = -1;
				while ((len = in.read(buffer)) > 0) {
					// 边读就边写
					out.write(buffer, 0, len);
				}
				in.close();
				out.write("\r\n".getBytes());
			}

			// 写结束符
			out.write((boundray + "--").getBytes());
			// 写完
			out.close();

			// 发起实际连接，获得服务器返回的结果
			ret = NetTool.getContent(conn.getInputStream(), "utf-8");
			System.out.println(ret);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return ret;

	}
}
